(function(){
    /**
	 * @class Bible.SearchGridPanel
	 * @extends Ext.grid.EditorGridPanel
	 */
	Bible.SearchGridPanel = Ext.extend(Ext.grid.GridPanel, {
        // while this is created for every BibleGrid can't be stateful
//        stateful: true,
//        stateID: 'Bible.SearchGridPanel',

        /**
         * @cfg {Bible.ReadContainer} activeReader
         */
        cls: 'bible-grid',
        //hideHeaders: true,
		stripeRows: true,
		//columnLines: true,
        autoExpandColumn: 'text',
		//loadMask: true,

		initComponent: function(){
            var me = this,
                colModel = new Ext.grid.ColumnModel({
                    columns: [
                        new Ext.grid.RowNumberer(),
                        {
                            id: 'text',
                            hideable: false,
                            menuDisabled: true,
                            header: 'Verset',
                            sortable: true,
                            dataIndex: 'text',
                            width: 200,
                            renderer: function(v, metaData, r, rowIndex, colIndex, store) {
                                v = Bible.rendererHighlight(v, metaData, r, rowIndex, colIndex, store);
                                return '<span class="verse-nr">(' + r.get('verse') + ')</span> ' + v;
                            }
                        }
                    ]
                });
            me.store = new Bible.data.BibleSearchStore();

            me.searchTypeStore = new Ext.data.ArrayStore({
                fields: ['id', 'name'],
                idIndex: 0,
                data : [
                    ['text', 'Text'],
                    ['any', 'ORICE cuvânt'],
                    ['all', 'TOATE cuvintele']
                ]
            });
            me.searchTypeCombo = new Ext.form.ComboBox({
                fieldLabel: i18n.searchType,
                anchor: '100%',
                //width: 200,
				displayField:'name',
                valueField: 'id',
                value: 'all',
                lastQuery: '',
                mode: 'local',
                selectOnFocus: true,
                forceSelection: true,
                triggerAction: 'all',
                editable: false,
                store: me.searchTypeStore,
                listeners: {
                    scope: me,
                    change: function(combo, newValue, oldValue){
                        console.debug('searchTypeCombo change', newValue, oldValue);
                        this.store.setBaseParam('type', newValue);
                    }
                }
            });

            me.searchIn = new Bible.form.ComboSearchFieldLocal({
                fieldLabel: i18n.searchIn,
				anchor: '100%',
                displayField:'name',
                valueField: 'id',
                lastQuery: '',
                mode: 'local',
                selectOnFocus: true,
                forceSelection: true,
                editable: true,
                typeAhead: true,
                allowBlank: true,
                triggerAction: 'all',
                emptyText: i18n.entireBible,
                listClass: 'x-combo-list-small x-combo-bible-books',
                //listWidth: 427,
				tpl: '<tpl for="."><div class="x-combo-list-item"><div>{id}</div>{name}</div></tpl>',
                store: new Bible.data.BibleBooksArrayStore(),
                listeners: {
                    scope: me,
                    clearfilter: function(){
                        console.debug('searchIn clearfilter');
                        this.store.setBaseParam('book', '');
                    },
                    change: function(combo, newValue, oldValue){
                        console.debug('searchIn change', newValue);
                        this.store.setBaseParam('book', newValue);
                    }
                }
            });

            me.searchField = new Ext.ux.form.SearchField({
                fieldLabel: i18n.search,
                store: this.store,
				anchor: '100%',
                filterType: true,
                onKeyup: true
            });
            me.store.searchField = me.searchField;

			Ext.apply(me, {
				hideMode: 'offsets',
				viewConfig: {
					autoFill: true,
					forceFit: true,
//					scrollOffset: 1,
                    templates: {
                        cell: new Ext.XTemplate(
                            '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} {css}" style="{style}" tabIndex="0" {cellAttr}>',
                                '<div class="x-grid3-cell-inner x-grid3-col-{id}" <tpl if="id != \'text\'">unselectable="on"</tpl> {attr}>{value}</div>',
                            '</td>'
                        )
                    }
				},
				sm: new Ext.grid.RowSelectionModel({
					singleSelect: true
				}),
				tbar: new Ext.Toolbar({
                    layout: 'fit',
                    style: {
                        padding: '5px 5px 2px 5px'
                    },
                    items: [{
                        xtype: 'container',
                        layout: 'form',
                        labelAlign: 'right',
                        hideMode: 'offsets',
                        items: [
                            me.searchTypeCombo,
                            me.searchIn,
                            me.searchField
                        ]
                    }]
                }),
                cm: colModel,
				bbar: new Ext.PagingToolbar({
                    buttonAlign: 'center',
                    pageSize: Bible.searchPageSize,
                    store: me.store
                })
			});

			Bible.SearchGridPanel.superclass.initComponent.call(me);
		},

		initEvents: function(){
            var me = this;
			Bible.SearchGridPanel.superclass.initEvents.apply(me, arguments);

            // TODO fix for chrome
//            if(Ext.isChrome){
//                console.warn('isChrome... fix combo width');
//                (function(){
//                    var c = this.getTopToolbar().get(0);
//                    c.setWidth(c.getWidth()-1);
//                    c.setWidth(c.getWidth()+1);
//                    console.warn('isChrome... tbar doLayout');
////                    c.doLayout(true);
//                }).defer(10, this);
//            }

            me.ctxMenu = new Ext.menu.Menu({
                items: [
//                    {
//                        text: i18n.copyText,
//                        icon: 'images/copy.png',
//                        scope: this,
//                        handler: function(){
//                            console.warn('TODO copyText');
//                        }
//                    },
//                    '-',
                    {
                        text: 'Deschide în coloana 1',
                        ref: 'openInFirst',
                        scope: me,
                        handler: me.openInFirstBibleGrid
                    },
                    {
                        text: 'Deschide în coloana 2',
                        ref: 'openInSecond',
                        scope: me,
                        handler: function(){
                            var bibleGrid = me.activeReader.secondGrid;
							me.activeReader.setBibleGridPage(me.selModel.getSelected(), me.searchField.getValue(), bibleGrid);
                        }
                    }
                ]
            });

            me.ctxMenu.on({
                scope: me,
                beforeshow: function(menu){
                    var actions = Bible.getActions(),
                        openInSecond = menu.openInSecond;
                    if(actions.l == 'hbox' || actions.l == 'vbox'){
                        openInSecond.show();
                    } else {
                        openInSecond.hide();
                    }
                }
            });

            me.on({
                scope: me,
                cellcontextmenu: function(thisGrid, rowIndex, cellIndex, e) {
                    e.stopEvent();
                    me.selModel.selectRow(rowIndex);
                    me.ctxMenu.showAt(e.getXY());
                },
                cellclick: function(grid, rowIndex, columIndex, e){
                    if(e.getTarget('.verse-nr')){
                        me.openInFirstBibleGrid();
                    }
                },
                celldblclick: function(grid, rowIndex, columnIndex, e){
                    console.debug('search grid celldblclick');
                    me.openInFirstBibleGrid();
                }
            });
		},

        openInFirstBibleGrid: function(){
            this.activeReader.setBibleGridPage(this.selModel.getSelected(), this.searchField.getValue());
        }
	});

    Ext.reg('searchgridpanel', Bible.SearchGridPanel);

})();
